package com.self.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.self.admin.feign.Auth2FeignClient;
import com.self.admin.mapper.SysUserMapper;
import com.self.admin.model.SysMenu;
import com.self.admin.model.SysUser;
import com.self.admin.model.SysUserRole;
import com.self.admin.service.SysMenuService;
import com.self.admin.service.SysUserRoleService;
import com.self.admin.service.SysUserService;
import com.self.admin.vo.LoginResultVo;
import com.self.common.constant.CommonConstants;
import com.self.common.dto.JwtTokenDto;
import com.self.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{

    @Autowired
    private Auth2FeignClient auth2FeignClient;

    @Value("${basic.token:Basic ZXhjaGFuZ2UtYXBpOmV4Y2hhbmdlLXNlY3JldA==}")
    private String basicToken;

    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public LoginResultVo login(String username, String password) {
        //调用认证系统，进行认证
        ResponseEntity<JwtTokenDto> clientToken = auth2FeignClient.getToken(CommonConstants.GRANT_TYPE_PASSWORD, username, password,
                CommonConstants.ADMIN_TYPE, basicToken);
        if (!clientToken.hasBody()){
            throw new BusinessException("获取token为空");
        }
        JwtTokenDto body = clientToken.getBody();
        if (body == null || StringUtils.isEmpty(body.getAccessToken())){
            throw new BusinessException("获取token为空");
        }
        String accessToken = body.getAccessToken();
        log.info("获取token:{}",accessToken);
        Jwt decode = JwtHelper.decode(accessToken);
        String claims = decode.getClaims();
        JSONObject jsonObject = JSONObject.parseObject(claims);
        String userName = jsonObject.getString("user_name");
        Long userId = Long.parseLong(userName);
        //由用户id，查询菜单权限
        List<SysMenu> menus = sysMenuService.queryMenuByUserId(userId);
        //由用户id，查询访问权限
        List<SimpleGrantedAuthority> authorities = jsonObject.getJSONArray("authorities").stream()
                .map(x -> new SimpleGrantedAuthority(x.toString())).collect(Collectors.toList());
        //保存到redis
        redisTemplate.opsForValue().set(CommonConstants.JWT_TOKEN_PROFIX+accessToken.hashCode(),userName,body.getExpireIn(), TimeUnit.SECONDS);

        return new LoginResultVo(body.getTokenType()+" "+body.getAccessToken(),menus,authorities);
    }

    @Override
    public Page<SysUser> getPage(Page<SysUser> page, String mobile, String fullname) {
        Page<SysUser> userPage = page(page,
                new LambdaQueryWrapper<SysUser>()
                        .likeRight(!StringUtils.isEmpty(mobile), SysUser::getMobile, mobile)
                        .likeRight(!StringUtils.isEmpty(fullname), SysUser::getFullname, fullname));
        if (!CollectionUtils.isEmpty(userPage.getRecords())){
            for (SysUser user : userPage.getRecords()){
                List<SysUserRole> list = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, user.getId()));
                if (!CollectionUtils.isEmpty(list)){
                    String collect = list.stream().map(sysUserRole -> sysUserRole.getRoleId().toString()).collect(Collectors.joining(","));
                    user.setRoleStrings(collect);
                }
            }
        }
        return userPage;
    }


    @Override
    public void addUser(SysUser sysUser) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        sysUser.setCreateBy(Long.parseLong(authentication.getPrincipal().toString()));
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        save(sysUser);
        String roleStrings = sysUser.getRoleStrings();
        if (StringUtils.hasText(roleStrings)){
            String[] split = roleStrings.split(",");
            List<SysUserRole> collect = Arrays.stream(split).map(roleId -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(sysUser.getId());
                sysUserRole.setRoleId(Long.parseLong(roleId));
                return sysUserRole;
            }).collect(Collectors.toList());
            sysUserRoleService.saveBatch(collect);
        }
    }

    @Transactional
    @Override
    public void deleteUser(List<Long> ids) {
        if (!CollectionUtils.isEmpty(ids)){
            removeByIds(ids);
            sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId,ids));
        }
    }

    @Transactional
    @Override
    public void updateUser(SysUser sysUser) {
        updateById(sysUser);
        sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,sysUser.getId()));
        String roleStrings = sysUser.getRoleStrings();
        if (StringUtils.hasText(roleStrings)){
            String[] split = roleStrings.split(",");
            List<SysUserRole> collect = Arrays.stream(split).map(roleId -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(sysUser.getId());
                sysUserRole.setRoleId(Long.parseLong(roleId));
                return sysUserRole;
            }).collect(Collectors.toList());
            sysUserRoleService.saveBatch(collect);
        }
    }
}
